package com.xuecheng.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.basic.domain.Category;
import com.xuecheng.basic.mappers.CategoryMapper;
import com.xuecheng.basic.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-18
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    //课程分类查询
    @Override
    public ResponseResult findTreeNodes() {
        //查询一级分类
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getParentid,0);
        Category category = this.getOne(qw);
        //转换对象
        CategoryVo vo = BeanHelper.copyProperties(category, CategoryVo.class);
        //查询所有二级分类
        List<CategoryVo> twos = findByParentId(vo.getId());//二级所需要的Parentid为一级的id
        vo.setCategoryTreeNodes(twos);
        //循环二级分类
        for (CategoryVo two : twos) {
            //根据二级分类.查询分类下的所有三级分类
            List<CategoryVo> threes = findByParentId(two.getId());
            two.setCategoryTreeNodes(threes);
        }
        return ResponseResult.okResult(vo);
    }

    //提取公共方法,根据parentid查询数据
    public List<CategoryVo> findByParentId(String parentId){
        LambdaQueryWrapper<Category> qw =new LambdaQueryWrapper<>();
        qw.eq(Category::getParentid,parentId);
        List<Category> list = this.list(qw);
        return BeanHelper.copyWithCollection(list,CategoryVo.class);
    }
}
